package com.byt.framlib.base;


import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.Window;

import androidx.annotation.NonNull;

import com.byt.framlib.BuildConfig;
import com.byt.framlib.R;
import com.byt.framlib.baseapp.AppManager;
import com.byt.framlib.basemvp.BasePresenter;
import com.byt.framlib.commonutils.NetWorkUtils;
import com.byt.framlib.commonutils.ToastUitl;
import com.byt.framlib.commonutils.permission.PermissionReq;
import com.byt.framlib.commonutils.rx.RxBus;
import com.byt.framlib.commonwidget.LoadingDialog;
import com.byt.framlib.commonwidget.LoadingTip;
import com.byt.framlib.commonwidget.NormalTitleBar;
import com.byt.framlib.commonwidget.StatusBarUtil;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.trello.rxlifecycle3.components.support.RxAppCompatActivity;

import java.lang.reflect.Method;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;

/**
 * 基类Actvity
 */
public abstract class BaseActivity<P extends BasePresenter> extends RxAppCompatActivity {

    private boolean isForegroud = false;
    protected Context mBContext; // 区别适配器里面的上下文对象
    protected Bundle mSavedInstanceState;
    protected View conentView;
    protected Unbinder mBinder;
    protected CompositeDisposable mCompositeDisposable = null;
    protected Disposable mDisposable = null;
    protected RefreshLayout refreshLayout = null;
    protected P mPresenter;
    protected boolean isShow = true;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (mCompositeDisposable == null) { // 为空或者是没有订阅
            mCompositeDisposable = new CompositeDisposable();
        }
        doBeforeSetcontentView();
        setContentView(getLayoutId());
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        conentView = inflater.inflate(getLayoutId(), null);
        mBinder = ButterKnife.bind(this);
        // 默认着色状态栏
        setStatusBar();
        mBContext = this;
        this.mSavedInstanceState = savedInstanceState;
        if (isShow){
            process(mSavedInstanceState);
        }
        mPresenter = initPreData();
        initView();
    }

    @Override
    public void onStart() {
        super.onStart();
        isForegroud = true;
    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }

    @Override
    public void onStop() {
        super.onStop();
        isForegroud = false;
    }

    /**
     * 设置layout前配置
     */
    private void doBeforeSetcontentView() {
        // 把actvity放到application栈中管理
        AppManager.getAppManager().addActivity(this);
        // 无标题
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        // 设置竖屏
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }

    /**
     * 添加Subscription
     *
     * @param disposable
     */
    public void addSubscription(Disposable disposable) {
        mCompositeDisposable.add(disposable);
    }

    public abstract int getLayoutId();

    /*********************子类实现*****************************/
    //获取布局文件

    //实例化前端的数据
    public abstract P initPreData();

    //初始化view
    public abstract void initView();


    protected void setStatusBar() {
        StatusBarUtil.setColor(this, getResources().getColor(R.color.white));
        changStatusIconCollor(true);
    }

    /**
     * 设置亮还是不亮
     * @param setDark
     */
    public void changStatusIconCollor(boolean setDark) {
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            View decorView = getWindow().getDecorView();
            if(decorView != null){
                int vis = decorView.getSystemUiVisibility();
                if(setDark){
                    vis |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
                } else{
                    vis &= ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
                }
                decorView.setSystemUiVisibility(vis);
            }
        }
    }
    /**
     * 隐藏虚拟按键，并且全屏
     */
    protected void hideBottomUIMenu() {
        //隐藏虚拟按键，并且全屏
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB && Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { // lower api
            View v = this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //for new api versions.
            View decorView = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_FULLSCREEN;
            decorView.setSystemUiVisibility(uiOptions);
        }
    }


    //获取状态栏的高度
    public int getTitleHight() {
        int statusBarHeight1 = -1;
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            statusBarHeight1 = getResources().getDimensionPixelSize(resourceId);
        }
        return statusBarHeight1;
    }

    //获取底部返回键等按键的高度
    public int getBackButtonHight() {
        int result = 0;
        if (hasNavBar(this)) {
            Resources res = this.getResources();
            int resourceId = res.getIdentifier("navigation_bar_height", "dimen", "android");
            if (resourceId > 0) {
                result = res.getDimensionPixelSize(resourceId);
            }
        }
        return result;
    }

    protected void process(Bundle savedInstanceState) {
        // 华为,OPPO机型在StatusBarUtil.setLightStatusBar后布局被顶到状态栏上去了
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            View content = ((ViewGroup) findViewById(android.R.id.content)).getChildAt(0);
            if (content != null && !isUseFullScreenMode()) {
                content.setFitsSystemWindows(true);
            }
        }
    }

    // 是否设置成透明状态栏，即就是全屏模式
    protected boolean isUseFullScreenMode() {
        return false;
    }

    //检查是否存在虚拟按键
    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    public static boolean hasNavBar(Context context) {
        Resources res = context.getResources();
        int resourceId = res.getIdentifier("config_showNavigationBar", "bool", "android");
        if (resourceId != 0) {
            boolean hasNav = res.getBoolean(resourceId);
            String sNavBarOverride = getNavBarOverride();
            if ("1".equals(sNavBarOverride)) {
                hasNav = false;
            } else if ("0".equals(sNavBarOverride)) {
                hasNav = true;
            }
            return hasNav;
        } else {
            return !ViewConfiguration.get(context).hasPermanentMenuKey();
        }
    }

    //检查虚拟按键是否被重写
    private static String getNavBarOverride() {
        String sNavBarOverride = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            try {
                Class c = Class.forName("android.os.SystemProperties");
                Method m = c.getDeclaredMethod("get", String.class);
                m.setAccessible(true);
                sNavBarOverride = (String) m.invoke(null, "qemu.hw.mainkeys");
            } catch (Throwable e) {
            }
        }
        return sNavBarOverride;
    }

    /**
     * 显示单选对话框
     *
     * @param title           标题
     * @param message         提示信息
     * @param checkedItem     默认选中
     * @param strings         选项数组
     * @param onClickListener 点击事件的监听
     */
    public void showRadioButtonDialog(String title, String message, String[] strings, int checkedItem, DialogInterface.OnClickListener onClickListener) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(title);
        if (!TextUtils.isEmpty(message)) {
            builder.setMessage(message);
        }
        builder.setSingleChoiceItems(strings, checkedItem, onClickListener);
        builder.create();
        builder.show();
    }

    /**
     * 通过Class跳转界面
     **/
    public void openActivity(Class<?> cls) {
        openActivity(cls, null);
    }

    /**
     * 通过Class跳转界面
     **/
    public void startActivityForResult(Class<?> cls, int requestCode) {
        startActivityForResult(cls, null, requestCode);
    }

    /**
     * 含有Bundle通过Class跳转界面
     **/
    public void startActivityForResult(Class<?> cls, Bundle bundle,
                                       int requestCode) {
        Intent intent = new Intent();
        intent.setClass(this, cls);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivityForResult(intent, requestCode);
    }

    /**
     * 含有Bundle通过Class跳转界面
     **/
    public void openActivity(Class<?> cls, Bundle bundle) {
        Intent intent = new Intent();
        intent.setClass(this, cls);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
    }

    /**
     * 含有Bundle通过Class跳转界面
     **/
    public void opensActivity(Class<?> cls, Bundle bundle) {
        Intent intent = new Intent();
        intent.setClass(this, cls);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
    }

    /**
     * 回调
     */
    public void setResultOk() {
        Intent intent = new Intent();
        setResult(RESULT_OK, intent);
        finish();
        this.overridePendingTransition(R.anim.stv_fadein,
                R.anim.stv_fadeout);
    }

    /**
     * 回调
     *
     * @param bundle
     */
    public void setResultOk(Bundle bundle) {
        Intent intent = new Intent();
        if (bundle != null) ;
        intent.putExtras(bundle);
        setResult(RESULT_OK, intent);
        finish();
        this.overridePendingTransition(R.anim.stv_fadein, R.anim.stv_fadeout);
    }

    /**
     * 开启浮动加载进度条
     */
    public void startProgressDialog() {
        LoadingDialog.showDialogForLoading(this);
    }

    /**
     * 开启浮动加载进度条
     *
     * @param msg
     */
    public void startProgressDialog(String msg) {
        LoadingDialog.showDialogForLoading(this, msg, true);
    }

    /**
     * 停止浮动加载进度条
     */
    public void stopProgressDialog() {
        LoadingDialog.cancelDialogForLoading();
    }

    /**
     * 短暂显示Toast提示(来自String)
     **/
    public void showShortToast(String text) {
        ToastUitl.showShort(text);
    }

    /**
     * 短暂显示Toast提示(id)
     **/
    public void showShortToast(int resId) {
        ToastUitl.showShort(resId);
    }

    /**
     * 长时间显示Toast提示(来自res)
     **/
    public void showLongToast(int resId) {
        ToastUitl.showLong(resId);
    }

    /**
     * 长时间显示Toast提示(来自String)
     **/
    public void showLongToast(String text) {
        ToastUitl.showLong(text);
    }

    /**
     * 带图片的toast
     *
     * @param text
     * @param res
     */
    public void showToastWithImg(String text, int res) {
        ToastUitl.showToastWithImg(text, res);
    }

    /**
     * 网络访问错误提醒
     */
    public void showNetErrorTip() {
        ToastUitl.showToastWithImg(getText(R.string.net_error).toString(), R.drawable.ic_wifi_off);
    }

    public void showNetErrorTip(String error) {
        ToastUitl.showToastWithImg(error, R.drawable.ic_wifi_off);
    }

    @Override
    protected void onResume() {
        //debug版本不统计crash
        isForegroud = true;
        if (!BuildConfig.DEBUG) {
//            MobclickAgent.onPageStart("BaseActivity");
//            MobclickAgent.onResume(mBContext);
        }
        super.onResume();
    }

    @Override
    protected void onPause() {
        //debug版本不统计crash
        if (!BuildConfig.DEBUG) {
//            MobclickAgent.onPageEnd("BaseActivity");
//            MobclickAgent.onPause(mBContext);
        }
        isForegroud = true;
        if (refreshLayout != null) {
            refreshLayout.finishRefresh();
            refreshLayout.finishLoadMore();
        }
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mCompositeDisposable != null) {
            mCompositeDisposable.dispose(); // 解除订阅，之后清除
            mCompositeDisposable.clear();
            RxBus.getDefault().removeAllStickyEvents();
        }
        if (mDisposable != null) {
            if (mDisposable.isDisposed()) {
                mDisposable.dispose();
                RxBus.getDefault().removeAllStickyEvents();
            }
        }
        if (mBinder != null) {
            mBinder.unbind();
        }
        AppManager.getAppManager().removeActivity(this);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionReq.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    /**
     * 获取是否存在NavigationBar，是否有虚拟按钮
     */
    public static boolean checkDeviceHasNavigationBar(Context context) {
        boolean hasNavigationBar = false;
        Resources rs = context.getResources();
        int id = rs.getIdentifier("config_showNavigationBar", "bool", "android");
        if (id > 0) {
            hasNavigationBar = rs.getBoolean(id);
        }
        try {
            Class systemPropertiesClass = Class.forName("android.os.SystemProperties");
            Method m = systemPropertiesClass.getMethod("get", String.class);
            String navBarOverride = (String) m.invoke(systemPropertiesClass, "qemu.hw.mainkeys");
            if ("1".equals(navBarOverride)) {
                hasNavigationBar = false;
            } else if ("0".equals(navBarOverride)) {
                hasNavigationBar = true;
            }
        } catch (Exception e) {

        }
        return hasNavigationBar;

    }

    /**
     * 获取虚拟按钮ActionBar的高度
     *
     * @param activity activity
     * @return ActionBar高度
     */
    public static int getActionBarHeight(Activity activity) {
        TypedValue tv = new TypedValue();
        if (activity.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
            return TypedValue.complexToDimensionPixelSize(tv.data, activity.getResources().getDisplayMetrics());
        }
        return 0;
    }

    public boolean isForegroud() {
        return isForegroud;
    }


    /**
     * 设置白色样式的状态栏和标题栏
     *
     * @param ntbTitle
     */
    public void setNtbTitle(NormalTitleBar ntbTitle, boolean visibility) {
        ntbTitle.setNtbWhiteBg(visibility);
    }

    /**
     * 显示错误页
     *
     * @param msg
     * @param loadingTip
     */
    public void showErrorView(String msg, LoadingTip loadingTip) {
        if (!TextUtils.isEmpty(msg)) {
            loadingTip.setTips(msg);
        }
        if (!NetWorkUtils.IsNetWorkEnable(mBContext)) {
            loadingTip.setLoadingTip(LoadingTip.LoadStatus.error);
        } else {
            loadingTip.setLoadingTip(LoadingTip.LoadStatus.sereverError);
        }
    }

    /**
     * 拨打电话（直接拨打电话）
     *
     * @param phoneNum 电话号码
    //     */
//    @SuppressLint("MissingPermission")
//    public void callPhone(String phoneNum) {
//        PermissionReq.with(this)
//                .permissions(Manifest.permission.CALL_PHONE)
//                .result(new ResultListener() {
//                    @Override
//                    public void onGranted() {
//                        showPhonDialog(phoneNum);
//                    }
//
//                    @Override
//                    public void onDenied() {
//                        showShortToast("请开启电话权限");
//                    }
//                }).request();
//    }

//    private void showPhonDialog(String phoneNum) {
//        if (!TextUtils.isEmpty(phoneNum) && FormatUtil.isMobileNO(phoneNum)) {
//            @SuppressLint("ResourceType")
//            NormalAlertDialog normalAlertDialog = new NormalAlertDialog.Builder(this)
//                    .setTitleVisible(false)
//                    .setContentText(phoneNum)
//                    .setContentTextSize(18)
//                    .setContentTextColor(R.color.color_464f66)
//                    .setRightButtonText("呼叫")
//                    .setRightButtonTextColor(R.color.color_staff_main)
//                    .setOnclickListener(new DialogOnClickListener() {
//                        @Override
//                        public void clickLeftButton(View view) {
//                        }
//
//                        @Override
//                        public void clickRightButton(View view) {
//                            Intent intent = new Intent(Intent.ACTION_CALL);
//                            Uri data = Uri.parse("tel:" + phoneNum);
//                            intent.setData(data);
//                            startActivity(intent);
//                        }
//                    }).build();
//            normalAlertDialog.show();
//        } else {
//            showShortToast("请输入正确的手机号");
//        }
//    }

    /**
     * 重写 getResource 方法，防止系统字体影响
     */
    @Override
    public Resources getResources() {//禁止app字体大小跟随系统字体大小调节
        Resources resources = super.getResources();
        if (resources != null && resources.getConfiguration().fontScale != 1.0f) {
            android.content.res.Configuration configuration = resources.getConfiguration();
            configuration.fontScale = 1.0f;
            resources.updateConfiguration(configuration, resources.getDisplayMetrics());
        }
        return resources;
    }

    public void setRefreshLayout(RefreshLayout refreshLayout) {
        this.refreshLayout = refreshLayout;
    }
}